﻿using NFine.Application._02_Weixin;
using NFine.Application.SystemManage;
using NFine.Code;
using NFine.Domain._02_ViewModel;
using NFine.Domain._03_Entity.Weixin;
using NFine.Domain.Entity.SystemManage;
using NFine.Web.App_Start;
using NFine.Web.App_Start._01_Handler;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Tencent;
using WeiXin.SDK;
using WeiXin.SDK.Entities;

namespace NFine.Web.Controllers
{
    public class WeixinController : Controller
    {
        private Log LOGGER = LogFactory.GetLogger(typeof(WeixinController).ToString());


        [HttpGet]
        [ActionName("Index")]
        public ActionResult Get(string signature, string timestamp, string nonce, string echostr)
        {
            //WeixinConfig.Register();
            if (string.IsNullOrEmpty(WeixinConfig.Token)) return Content("请先设置Token！");
            var ent = "";
            if (!BasicAPI.CheckSignature(signature, timestamp, nonce, WeixinConfig.Token, out ent))
            {
                return Content("参数错误！");
            }
            return Content(echostr); //返回随机字符串则表示验证通过
        }

        /*
        appID : wxaffb239f7107248b
        appsecret : c5a58111a406bb06409607429b86d1d2
            */

        [HttpPost]
        [ActionName("Index")]
        public ActionResult Post(string signature, string timestamp, string nonce, string echostr)
        {
            //WeixinConfig.Register();
            WeixinMessage message = null;
            var safeMode = Request.QueryString.Get("encrypt_type") == "aes";
            using (var streamReader = new StreamReader(Request.InputStream))
            {
                var decryptMsg = string.Empty;
                var msg = streamReader.ReadToEnd();

                #region 解密

                if (safeMode)
                {
                    var msg_signature = Request.QueryString.Get("msg_signature");
                    var wxBizMsgCrypt = new WXBizMsgCrypt(WeixinConfig.Token, WeixinConfig.EncodingAESKey,
                        WeixinConfig.AppID);
                    var ret = wxBizMsgCrypt.DecryptMsg(msg_signature, timestamp, nonce, msg, ref decryptMsg);
                    if (ret != 0) //解密失败
                    {
                        //TODO：开发者解密失败的业务处理逻辑
                        LOGGER.Error(string.Format("\r\ndecrypt message return {0}, request body {1}", ret, msg));
                    }
                }
                else
                {
                    decryptMsg = msg;
                }

                #endregion

                message = AcceptMessageAPI.Parse(decryptMsg);
            }
            var response = new WeixinExecutor().Execute(message);
            var encryptMsg = string.Empty;

            #region 加密

            if (safeMode)
            {
                var msg_signature = Request.QueryString.Get("msg_signature");
                var wxBizMsgCrypt = new WXBizMsgCrypt(WeixinConfig.Token, WeixinConfig.EncodingAESKey,
                    WeixinConfig.AppID);
                var ret = wxBizMsgCrypt.EncryptMsg(response, timestamp, nonce, ref encryptMsg);
                if (ret != 0) //加密失败
                {
                    //TODO：开发者加密失败的业务处理逻辑
                    LOGGER.Error(string.Format("\r\nencrypt message return {0}, response body {1}", ret, response));
                }
            }
            else
            {
                encryptMsg = response;
            }

            #endregion

           // LOGGER.Debug("用户信息授权AAAA");

            return new ContentResult
            {
                Content = encryptMsg,
                ContentType = "text/xml",
                ContentEncoding = UTF8Encoding.UTF8
            };
        }
        /// <summary>
        /// 微信授权后回调方法
        /// </summary>
        /// <param name="code"></param>
        /// <param name="state"></param>
        /// <param name="returnUrl"></param>
        /// <returns></returns>
        public ActionResult AuthorizeCallBack(string code, string state, string returnUrl)
        {
            if (string.IsNullOrEmpty(code))
            {
                return Content("您拒绝了授权！");
            }
            if (state != Session["State"] as string)
            {
                return Content("验证失败！");
            }
            var accessToken = OAuth2API.GetAccessToken(code, WeixinConfig.AppID, WeixinConfig.AppSecret);
            //LOGGER.Debug(string.Format("\r\n授权回调页获取AccessToken：{0}", accessToken.ToString()));
            if (!string.IsNullOrWhiteSpace(accessToken.access_token))
            {
                dynamic d = OAuth2API.GetUserInfo(accessToken.access_token, accessToken.openid, "zh_CN");

                //Task task = new Task(() => disposeUserInfo(d));
                //task.Start();
                //disposeUserInfo(d);
                LOGGER.Debug(string.Format("\r\n获取用户信息：{0}", d.ToString()));

                return disposeUserInfo(d, returnUrl);
            }
            else
            {
                return Content("错误：" + accessToken.errmsg);
            }
        }

        private ActionResult disposeUserInfo(dynamic d, string returnUrl)
        {
            UserApp app = new UserApp();
            UserEntity userEntity = app.GetByOpenid(d.openid);
            if (userEntity == null)
            {
                WechatInfoApp _wechatInfoApp = new WechatInfoApp();
                WechatInfoEntity entity = _wechatInfoApp.GetByOpenId(d.openid);
                if (entity==null)
                {
                    entity = new WechatInfoEntity();
                    entity.F_openid = d.openid.ToString();
                    entity.F_nickname = d.nickname.ToString();
                    entity.F_province = d.province.ToString();
                    entity.F_city = d.city.ToString();
                    entity.F_country = d.country.ToString();
                    entity.F_headimgurl = d.headimgurl.ToString();
                    entity.F_sex = d.sex.ToString();
                    entity.F_qrscene = 0;
                    //_wechatInfoApp.SubmitForm(entity, 0);
                }

                //Session["weinfo"] = entity;

                userEntity = new UserEntity();
                userEntity.F_Gender = !(entity.F_sex=="男");
                userEntity.F_RealName=entity.F_nickname;
                UserLogOnEntity userLogOnEntity = new UserLogOnEntity();
                userLogOnEntity.F_UserPassword = entity.F_qrscene.ToString("000000");
                app.InitWeixinUser(entity, userEntity, userLogOnEntity);

                //跳转用户的信息完善页面
                return Redirect(returnUrl);
            }
            else
            {
                //更新一下用户的头像信息
                if (!userEntity.F_HeadIcon.Equals(d.headimgurl.ToString())) {
                    userEntity.F_HeadIcon = d.headimgurl.ToString();
                    app.UpdateForm(userEntity);
                }
                //进行用户登录信息的完善，然后跳转到相应页面
                OperatorModel operatorModel = new OperatorModel();
                operatorModel.UserId = userEntity.F_Id;
                operatorModel.UserCode = userEntity.F_Account;
                operatorModel.UserName = userEntity.F_RealName;
                operatorModel.CompanyId = userEntity.F_OrganizeId;
                operatorModel.USERHEAD = userEntity.F_HeadIcon;
                operatorModel.DepartmentId = userEntity.F_DepartmentId;
                operatorModel.RoleId = userEntity.F_RoleId;
                operatorModel.LoginIPAddress = Net.Ip;
                operatorModel.LoginIPAddressName = Net.GetLocation(operatorModel.LoginIPAddress);
                operatorModel.LoginTime = DateTime.Now;
                operatorModel.LoginToken = DESEncrypt.Encrypt(Guid.NewGuid().ToString());
                operatorModel.IsOrder = userEntity.F_DutyId != "1";
                operatorModel.phone = userEntity.F_MobilePhone;
                operatorModel.IsSystem = "admin".Equals(userEntity.F_Account);// userEntity.F_RoleId != Configs.GetValue("MemberRoleId");
                OperatorProvider.Provider.AddCurrent(operatorModel);
                return Redirect(returnUrl);
            }
        }
        public ActionResult NeedToUser(string uri)
        {
            var state = "hbyys-" + DateTime.Now.Millisecond;
            Session["state"] = state;
            var authorizeUrl = OAuth2API.GetAuthorizeUrl(WeixinConfig.AppID,
                WeixinConfig.Domain + "/Weixin/AuthorizeCallBack?returnUrl=" +
                System.Web.HttpUtility.UrlEncode(WeixinConfig.Domain + uri), state, "snsapi_userinfo");
            //LOGGER.Debug(string.Format("\r\n跳转授权页地址：{0}", authorizeUrl));
            return Redirect(authorizeUrl);
        }
        public ActionResult wait()
        {

            return View();
        }

        public ActionResult baiya()
        {
            return View();
        }

        public ActionResult News()
        {
            return View();
        }





    }
}
